package com.zifeng.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zifeng.common.R;
import com.zifeng.dao.OrderDao;
import com.zifeng.pojo.Order;
import com.zifeng.service.IOrderService;
import com.zifeng.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * 船舶订单Controller
 * 
 * @author zifeng
 * @date 2025-03-27
 */
@RestController
@RequestMapping("/order")
public class OrderController
{
    @Autowired
    private IOrderService orderService;

    @Autowired
    private OrderDao orderDao;

//    @Autowired
//    private KafkaTemplate<String, String> kafkaTemplate;

    @PostMapping("/addwithblock")
    public R addOrderWithBlock(@RequestBody Order order) {
        orderService.insertOrder(order);

        // 为了保证订单创建成功 + 买卖双方余额修改成功 + 船只归属更新成功这个分布式事务和区块链事务的一致性
        // 所以采用RocketMQ的事务消息
        // Spring整合Kafka的发送消息方式
//        kafkaTemplate.send("order-topic", JSON.toJSONString(order));

        // 原生Kafka发送消息方式
//        Properties properties = new Properties();
//        properties.setProperty("bootstrap.servers", "localhost:9092");
//        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
//        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
//        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
//        ProducerRecord<String, String> record = new ProducerRecord<>("order-topic", JSON.toJSONString(order));
//        producer.send(record, (metadata, exception) -> {
//            if (exception != null) {
//                System.err.println("发送消息失败: " + exception.getMessage());
//            } else {
//                System.out.println("消息发送成功: " + metadata.toString());
//            }
//        });
        return R.ok();
    }

    /**
     * 后台管理：统计一个月的订单数量
     * @param year
     * @param month
     * @return
     */
    @RequestMapping("/count/{year}/{month}")
    public R countByMonth(@PathVariable Integer year, @PathVariable Integer month) {
        Long count = orderService.countByMonth(year, month);
        return R.ok().put("count", count);
    }

    /**
     * 后台管理：查询订单总数
     * @return
     */
    @RequestMapping("/count")
    public R count() {
        Long count = orderDao.selectCount(null);
        return R.ok().put("count", count);
    }

    /**
     * 后台管理：模糊查询
     * @param params
     * @return
     * @throws IOException
     */
    @RequestMapping("/listByFuzzyQuery")
    public R listByFuzzyQuery(@RequestParam Map<String, String> params) throws IOException {

        String data = params.get("data");
        if (StringUtils.isEmpty(data)) {
            return R.error(401, "查询参数不能为空");
        }
        ObjectMapper om = new ObjectMapper();
        Order order = om.readValue(data, Order.class);
        List<Order> list = orderDao.fuzzyQuery(order);
        list = judgeDate(order.getCreateAt(), order.getUpdateAt(), list);
        int currPage = Integer.parseInt(params.get("page"));
        int pageSize = Integer.parseInt(params.get("limit"));
        PageUtils page = new PageUtils(list, list.size(), pageSize, currPage);

        //从第几条数据开始
        int firstIndex = (currPage - 1) * pageSize;
        //到第几条数据结束
        int lastIndex = currPage * pageSize;
        //当最后索引大于总数时，要进行设置最后索引
        if (lastIndex > page.getTotalCount()) {
            lastIndex = page.getTotalCount();
        }
        //当只有一条数据时
        if (lastIndex == firstIndex) {
            page.setList(page.getList());
        }else {
            page.setList(page.getList().subList(firstIndex, lastIndex));
        }

        return R.ok().put("page", page);
    }

    private static List<Order> judgeDate(Date beginDate, Date endDate, List<Order> list) {
        // 日期判断
        List<Order> resList = new ArrayList<>();
        if (beginDate != null && endDate == null) {
            for (Order item : list) {
                Date createAt = item.getCreateAt();
                int res = createAt.compareTo(beginDate);
                if (res == 1 || res == 0) {
                    resList.add(item);
                }
            }
            list = new ArrayList<>(resList);
        }else if (beginDate == null && endDate != null) {
            for (Order item : list) {
                Date updateAt = item.getUpdateAt();
                if(updateAt == null) {
                    resList.add(item);
                }else {
                    int res = updateAt.compareTo(endDate);
                    if (res == -1 || res == 0) {
                        resList.add(item);
                    }
                }
                list = new ArrayList<>(resList);
            }
        } else if (beginDate != null && endDate != null) {
            for (Order item : list) {
                int res1 = item.getCreateAt().compareTo(beginDate);
                Date updateAt = item.getUpdateAt();
                if(updateAt == null && (res1 == 1 || res1 == 0)) {
                    resList.add(item);
                }else {
                    int res2 = updateAt.compareTo(endDate);
                    if ((res1 == 1 || res1 == 0) && (res2 == -1 || res2 == 0)) {
                        resList.add(item);
                    }
                }
            }
            list = new ArrayList<>(resList);
        }
        return list;
    }

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping(value = "/{id}")
    public R getOrder(@PathVariable("id") Long id)
    {
        Order order = orderService.selectOrderById(id);
        return R.ok().put("order", order);
    }

    /**
     * 新增订单
     */
    @PostMapping
    public R add(@RequestBody Order order)
    {
        int i = orderService.insertOrder(order);
        return R.ok();
    }

    /**
     * 修改订单
     */
    @PutMapping
    public R edit(@RequestBody Order order)
    {
        int i = orderService.updateOrder(order);
        return R.ok();
    }

    /**
     * 删除订单
     */
	@DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids)
    {
        int i = orderService.deleteOrderByIds(ids);
        return R.ok();
    }
}
